package com.leyou.user.service;

import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.utils.CodecUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    Logger logger = LoggerFactory.getLogger(UserService.class);

    public Boolean checkData(String data, Integer type) {


        User record = new User();

        switch (type){
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
        }

        return this.userMapper.selectCount(record)!=1;
    }


    static final String KEY_PREFIX = "user:code:phone:";

    public Boolean sendVerifyCode(String phone) {

        try {
            Map<String, String> msg = new HashMap<>();
            msg.put("phone",phone);

            //使用工具生成验证码
            String code = NumberUtils.generateCode(6);
            msg.put("code",code);

            amqpTemplate.convertAndSend("ly.sms.exchange","sms.verify.code",msg);


            //给redis中存入一个和手机号相关的验证码，5分钟有效
            redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);

            return true;
        } catch (AmqpException e) {
            e.printStackTrace();
        }
        return null;
    }

    //根据输入的电话号，和code把发出的code进行校验
    public Boolean register(User user, String code) {

        //获取到存储的redis中的code，

        String storeCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());

        if (null==storeCode || !storeCode.equals(code)){//判断如果没有取到值或者验证码错误
            return null;
        }

        user.setCreated(new Date());
        String salt = CodecUtils.generateSalt();

        user.setSalt(salt);

        String newPassword = CodecUtils.md5Hex(user.getPassword(), salt);

        user.setPassword(newPassword);

        Boolean boo = this.userMapper.insertSelective(user)==1;


        // 如果注册成功，删除redis中的code
        if (boo) {
            try {
                this.redisTemplate.delete(KEY_PREFIX + user.getPhone());
            } catch (Exception e) {
                logger.error("删除缓存验证码失败，code：{}", code, e);
            }
        }

        return true;
    }

    public User queryUser(String username, String password) {
        User recode = new User();
        recode.setUsername(username);

        User user = this.userMapper.selectOne(recode);

        if (null!=user){
            String salt = user.getSalt();
            String inputPass = CodecUtils.md5Hex(password,salt);
            if (user.getPassword().equals(inputPass)){//输入的密码经过 加盐加密后变成加密的密码，如果加密的密码和数据库比对成功则登录成功
                return user;
            }
        }


        return null;
    }
}
